package com.example.logTracer;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @Describe : 雪花数
 * @Author : zyx
 * @Date : 2023/12/5 10:02
 * @Version : 1.0
 **/
public class SnowflakeId {

    private final static long twepoch = 1701741577779L;

    /**
     * 机器标识位数
     */
    private final static long workerIdBits = 5L;

    /**
     * 支持的最大机器id 31位
     */
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /**
     * 毫秒内自增数
     */
    private final static long sequenceBits = 12L;

    /**
     * 机器id左移12位
     */
    private final static long workerIdShift = sequenceBits;

    /**
     * 时间毫秒左移22位
     */
    private final static long timestampLeftShift = sequenceBits+10L;

    /**
     * sequence掩码，确保sequence不会超出上限
     */
    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);

    /**
     * 上次时间戳
     */
    private static long lastTimestamp = -1L;

    /**
     * 序列
     */
    private long sequence = 0L;

    /**
     * 服务器id
     */
    private long workerId;
    private static long workerMask = -1L ^ (-1L << workerIdBits);

    private static class Holder{
        private static final SnowflakeId INSTANCE = new SnowflakeId();
    }

    public static SnowflakeId getInstance(){
        return Holder.INSTANCE;
    }

    private SnowflakeId(){
        this.workerId = getMachineNo();
        this.workerId = workerId & workerMask;
    }

    public synchronized long getNextId(){
        // 获取时间戳
        long timestamp = timeGen();
        // 如果时间戳小于上次时间戳则报错
        if (timestamp < lastTimestamp){
            try {
                throw new Exception("Clock moved backwards. Refusing to generate id for "+(lastTimestamp - timestamp) +" milliseconds");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        // 如果时间戳与上次时间戳相同
        if (lastTimestamp == timestamp){
            // 当前毫秒内，则+1，与sequenceMask确保sequence不会超出上限
            sequence = (sequence+1) & sequenceMask;
            if (sequence == 0){
                // 当前毫秒内计数满了，则等待下一秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        }else {
            sequence = 0;
        }
        lastTimestamp = timestamp;

        // id偏移组合生成最终的id，并返回id
        long nextId = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
        return nextId;
    }

    /**
     * 再次获取时间戳，直到获取的时间戳与现有的不同
     * @param lastTimestamp
     * @return
     */
    private long tilNextMillis(final long lastTimestamp){
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp){
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen(){
        return System.currentTimeMillis();
    }

    /**
     * 获取机器码
     * @return
     */
    private long getMachineNo() {
        long machinePiece;
        StringBuffer sb = new StringBuffer();
        Enumeration<NetworkInterface> e = null;
        try {
            e = NetworkInterface.getNetworkInterfaces();
        }catch (SocketException e1){
            e1.printStackTrace();
        }
        while (e.hasMoreElements()){
            NetworkInterface ni = e.nextElement();
            sb.append(ni.toString());
        }
        machinePiece = sb.toString().hashCode();
        return machinePiece;
    }

}
